package edu.ntu.cloudroid.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import edu.ntu.cloudroid.model.IDs;
import edu.ntu.cloudroid.model.UserData;
import edu.ntu.cloudroid.model.data.DetachedData;
import edu.ntu.cloudroid.model.friend.FriendInfo;
import edu.ntu.cloudroid.model.friend.GroupInfo;
import edu.ntu.cloudroid.model.policy.PolicyInfo;
import edu.ntu.cloudroid.model.profile.ProfileInfo;
import edu.ntu.cloudroid.nongui.util.TimeCounter;
import edu.ntu.cloudroid.server.backendservice.DataService;

public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static Logger logger = Logger.getLogger(UploadServlet.class
			.getName());
	public static final String METHOD_NAME = "uploadServlet";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ObjectInputStream ois = new ObjectInputStream(req.getInputStream());
		
		//System.out.print("-");
		//long begin = System.currentTimeMillis();
		
		try {
			UserData data = (UserData)ois.readObject();
			if (data.getUploadID() == IDs.UploadID.Profile){
				//logger.info("Adding profile");
				Uploader.uploadProfile((ProfileInfo)data);
			}
			else if (data.getUploadID() == IDs.UploadID.Policy){
				//logger.info("Adding policy");
				Uploader.uploadPolicy((PolicyInfo)data);
			}
			else if (data.getUploadID() == IDs.UploadID.Friend){
				//logger.info("Adding friend");
				Uploader.uploadFriend((FriendInfo)data);
			}
			else if (data.getUploadID() == IDs.UploadID.Group)
				Uploader.uploadGroup((GroupInfo)data);
			else if (data.getUploadID() == IDs.UploadID.Data) {
				//logger.info("Adding data");
				Uploader.uploadData((DetachedData)data);
			}
			
			/*DetachedData data = (DetachedData) ois.readObject();
			DataService.addData(data.toGAEData());*/
		}
		catch (Exception e){
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
		//System.out.println(System.currentTimeMillis() - begin);
	}
}